package com.axend.vetwavve.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.axend.lib_base.base.vm.BaseViewModel
import com.axend.lib_room.entity.PetInfoEntity
import com.axend.lib_room.manager.PetInfoManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext

class AddOrEditRecordViewModel : BaseViewModel() {

    private var _isAdd: MutableLiveData<Boolean> = MutableLiveData()
    val isAdd: LiveData<Boolean> get() = _isAdd


    /**
     * 设置是否新增
     */
    fun setIsAdd(isAdd: Boolean) {
        _isAdd.value = isAdd
    }


    /**
     * 提交参数到数据库
     */
    fun submitParamsToDataBase(petInfoEntity: PetInfoEntity, callback: (petInfoEntity: PetInfoEntity) -> Unit) {
        launchOnUI {
            withContext(Dispatchers.IO) {
                try {
                    PetInfoManager.savePetInfo(petInfoEntity)
                }catch (e: Exception){
                    e.printStackTrace()
                }
            }
//            delay(2000L)
            callback(petInfoEntity)
        }
    }


    /**
     * 更新数据到数据库
     */
    fun updateParamsToDataBase(petInfoEntity: PetInfoEntity, callback: (petInfoEntity: PetInfoEntity) -> Unit) {
        launchOnUI {
            withContext(Dispatchers.IO) {
                try {
                    PetInfoManager.updatePetInfoItem(petInfoEntity)
                }catch (e: Exception){
                    e.printStackTrace()
                }
            }
//            delay(2000L)
            callback(petInfoEntity)
        }
    }
}